<template>
  <div class="app-container">
      <div class="title">
        <div v-if="this.$route.params&&this.$route.params.id">修改讲师</div>
          <div v-else>添加讲师</div>
      </div>
    <el-form ref="teacherForm" :model="teacher" :rules="rules" label-width="120px">
      <el-form-item label="讲师名称" prop="name">
        <el-input v-model="teacher.name"/>
      </el-form-item>
        <el-form-item label="讲师排序" prop="sort">
         <el-input-number v-model="teacher.sort" controls-position="right" :min="1"></el-input-number>
      </el-form-item>
      <el-form-item label="讲师头衔" prop="level">
        <el-select v-model="teacher.level" placeholder="请选择">
          <el-option label="高级讲师" :value="1"/>
          <el-option label="首席讲师" :value="2"/>
        </el-select>
      </el-form-item>
            <el-form-item label="讲师资历" prop="career">
        <el-input v-model="teacher.career"/>
      </el-form-item>
       <el-form-item label="讲师简介" prop="intro">
        <el-input v-model="teacher.intro" type="textarea" :rows="10"/>
      </el-form-item>
      <!-- 头像 -->
    <el-form-item label="讲师头像" >
        <PanThumb :image="teacher.avatar"></PanThumb>
        <el-button type="primary" class="el-icon-upload" @click="ImageCropperShow=true">更换头像</el-button>
        <!-- 剪裁头像 -->
        <!-- 
          key:头像剪裁插件的唯一标识
          url：上传图片的API
          field：请求API时需要发送的字段名（后端API约定）
          close：关闭头像剪裁插件调用的方法
          crop-upload-success：头像上传成功是的回调方法
         -->
        <ImageCropper 
        v-show="ImageCropperShow" 
        @close="close"
        :width="150"
        :height="150"
        :key="imageCropperKey"
        :url="`${BASE_URL}/file/upload?host=avatar`"
        field="file"
        @crop-upload-success="cropSuccess"
        >
        
        </ImageCropper>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">保存</el-button>
     
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import teacherApi from '@/api/teacher'
import PanThumb from '@/components/PanThumb'
import ImageCropper from '@/components/ImageCropper'
export default {
  components:{PanThumb,ImageCropper},//注册组件
  data() {
    
    return {
      BASE_URL:process.env.BASE_API,//获取dev配置文件中的API地址
      imageCropperKey:1,//头像剪裁组件的key
      ImageCropperShow:false,//头像剪裁插件是否显示
      teacher: {avatar:'http://hopu-learning.oss-cn-hangzhou.aliyuncs.com/avatar_default.png'},
       rules: {
          name: [
            { required: true, message: '请输入讲师姓名', trigger: 'blur' },
            { max: 5, message: '长度最大为5个字符', trigger: 'blur' }
          ],
          sort: [
            { type:"number", message: '排序必须是数字', trigger: 'blur' },
            { required: true, message: '请输入序号', trigger: 'blur' }
          ],
          level: [
            { required: true, message: '请选择讲师头衔', trigger: 'blur' }
          ],
          career: [
            {required: true, message: '请输入讲师资历', trigger: 'blur' }
          ],
          intro: [
            {required: true, message: '请输入讲师简介', trigger: 'blur' }
          ]
        }
    }
  },
  watch:{
$route(to,from){
 this.init()
}
  },
  created() {
this.init()
  },
  methods: {
    //   提交表单
    onSubmit() {
this.$refs['teacherForm'].validate((valid) => { 
     if (valid) {
         // 判断执行的是更新还是添加
      if(this.teacher.id){
        // console.log("执行编辑")
        this.updateTeache()
      }else{
        // console.log("执行添加")
        this.addTeacher()
      }
     }

});
    },
    // 添加讲师
  addTeacher(){
    teacherApi.addTeacher(this.teacher).then(res=>{
        // 提示成功信息
               this.$message({
            type: 'success',
            message: '添加成功!'
          });
        //   跳转至讲师列表页面   通过编程式导航
        this.$router.push({path:"/teacher"})
    })
  },
  // 更新讲师
  updateTeache(){
    // 调用更新API
teacherApi.updateTeache(this.teacher).then(res=>{
  // 更新成功后提示
        this.$message({
            type: 'success',
            message: '更新成功!'
          });
           //   跳转至讲师列表页面   通过编程式导航
        this.$router.push({path:"/teacher"})
})
  },

  // 根据id获取讲师信息
  getTeacher(id){

    teacherApi.getTeacher(id).then(res=>{
      // 将讲师信息添加到表单中
      this.teacher=res.data
    }).catch(err=>{
      this.$message({
            type: 'error',
            message: '获取数据失败!'
          });
    })

  },
  // 切换清空
  init(){
  if(this.$route.params&&this.$route.params.id){
    // 执行更新操作
    // console.log("执行更新操作")
    // 根据id调用讲师API
    const id=this.$route.params.id
    this.getTeacher(id)
  }else{
        // 执行添加操作
    // console.log("执行添加操作")
    this.teacher={
    avatar:'http://hopu-learning.oss-cn-hangzhou.aliyuncs.com/avatar_default.png'
    }
  }
  },
  cropSuccess(data){
console.log(data)
// 上传成功关闭剪裁插件
 this.ImageCropperShow=false
//  显示上传后的头像图片
this.teacher.avatar=data.ossUrl;

// 修改头像剪裁插件的key值，使其进行初始化
this.imageCropperKey=this.imageCropperKey+1
  },
    close() {
   this.ImageCropperShow=false
   // 修改头像剪裁插件的key值，使其进行初始化
this.imageCropperKey=this.imageCropperKey+1
    }
  }
}
</script>

<style scoped>
.line{
  text-align: center;
}
.title{
    font-weight: 700;
    font-size: 19px;
    color: #000;
    margin-bottom: 10px;
    margin-left: 10px;
}
</style>

